<template>

  <v-card :title="title" @submit="submit" @reset="reset">
    <v-form ref="form" :form-title="formTitle" :rules="rules" :form-data="formData"/>
  </v-card>
</template>

<script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.formData.pwdNew !== '') {
          this.$refs.form.$refs.form.validateField('pwdNewTwo')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formData.pwdNew) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      imageUrl: '',
      title: '创建',
      rules: {
        pwdNew: [
          { validator: validatePass, trigger: 'blur' }
        ],
        pwdNewTwo: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      roleList: [],
      formData: {}
    }
  },
  computed: {
    formTitle() {
      return ([
        {
          en: 'username',
          cn: '用户名'
        },
        {
          en: 'name',
          cn: '名称'
        },
        {
          en: 'role_id',
          cn: '角色',
          type: 'select',
          list: this.roleList
        },
        {
          en: 'pwdNew',
          cn: '密码',
          type: 'password'
        },
        {
          en: 'pwdNewTwo',
          cn: '重复密码',
          type: 'password'
        }
      ])
    }
  },
  activated() {
    this.getRoleList()
    this.$emit('childTitle', this.$route.meta.title1)
  },
  methods: {
    // 获取角色列表
    getRoleList() {
      this.$get('action/PositionCtrl/dataGrid', { rows: 50 })
        .then(res => {
          this.roleList = res.data.list.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
        })
    },

    back() {
      this.$router.go(-1)
    },

    submit() {
      const data = {
        name: this.formData.name,
        username: this.formData.username,
        roleId: this.formData.role_id,
        pwdNew: this.formData.pwdNew,
        pwdNewTwo: this.formData.pwdNewTwo
      }
      this.$post('action/user/found', data)
        .then(res => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
        })
    },
    reset() {
      this.formData = {}
    }
  }

}
</script>

<style rel="stylesheet/scss" lang="scss">

</style>
